<template>
  <div class="interview-session-container">
    <!-- 面试头部信息 -->
    <div class="interview-header">
      <div class="company-info">
        <h1>{{ interview.company || '面试进行中' }}</h1>
        <p>{{ interview.position || '正在加载...' }}</p>
      </div>
      <div class="interview-progress">
        <span>第 {{ currentStageIndex + 1 }}/{{ stages.length }} 阶段</span>
        <el-progress 
          :percentage="progressPercentage" 
          :stroke-width="6"
          color="#6753C0"
        />
      </div>
    </div>
    
    <!-- 面试状态提示 -->
    <div v-if="isInterviewLocked" class="interview-status-alert">
      <el-alert
        :title="statusMessage"
        type="info"
        show-icon
        :closable="false"
        effect="dark"
      >
        <template #default>
          <p>面试已完成，请等待HR审核结果</p>
          <div v-if="interviewProgress.total_video_questions > 0" class="progress-info">
            <span>视频题目完成进度: {{ interviewProgress.answered_video_questions }}/{{ interviewProgress.total_video_questions }}</span>
            <el-progress :percentage="interviewProgress.percentage" :stroke-width="4" />
          </div>
        </template>
      </el-alert>
    </div>
    
    <!-- 阶段导航 -->
    <div class="stage-navigation">
      <el-steps 
        :active="currentStageIndex" 
        :space="200"
        finish-status="success"
        class="stage-steps"
      >
        <el-step 
          v-for="(stage, index) in stages" 
          :key="stage.id"
          :title="stage.name"
          :description="stage.description"
          :icon="stage.icon"
        />
      </el-steps>
    </div>
    
    <!-- 阶段内容 -->
    <div class="stage-content" :class="{ 'disabled': isInterviewLocked }">
      <!-- 简历匹配阶段 -->
      <div v-if="currentStage.id === 'resume' && !isInterviewLocked" class="resume-stage">
        <div class="stage-header">
          <h2>简历匹配验证</h2>
          <p>请确认您的简历信息并录制30秒自我介绍</p>
        </div>
        
        <div class="resume-section">
          <div class="resume-display">
            <h3>简历信息</h3>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="姓名">{{ candidateInfo.name }}</el-descriptions-item>
              <el-descriptions-item label="邮箱">{{ candidateInfo.email }}</el-descriptions-item>
              <el-descriptions-item label="工作经验">{{ candidateInfo.experience }}</el-descriptions-item>
              <el-descriptions-item label="学历">{{ candidateInfo.education }}</el-descriptions-item>
              <el-descriptions-item label="技能标签" :span="2">
                <el-tag v-for="skill in candidateInfo.skills" :key="skill" class="skill-tag">
                  {{ skill }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </div>
          
          <div class="self-introduction">
            <h3>30秒自我介绍</h3>
            <div class="video-recording">
              <div class="camera-preview" v-if="!selfIntroductionVideo">
                <video 
                  ref="previewVideo" 
                  autoplay 
                  muted 
                  width="400"
                  height="300"
                  style="border-radius: 8px; background: #000;"
                ></video>
                <div class="preview-controls">
                  <el-button 
                    type="info" 
                    size="small" 
                    @click="startCameraPreview"
                    v-if="!isCameraPreviewOn"
                  >
                    <el-icon><VideoCamera /></el-icon>
                    开启摄像头预览
                  </el-button>
                  <el-button 
                    type="warning" 
                    size="small" 
                    @click="stopCameraPreview"
                    v-if="isCameraPreviewOn"
                  >
                    <el-icon><VideoPause /></el-icon>
                    关闭摄像头预览
                  </el-button>
                </div>
              </div>
              
              <div class="recording-controls">
                <el-button 
                  type="primary" 
                  @click="startSelfIntroduction"
                  :disabled="isRecording"
                  size="large"
                >
                  <el-icon><VideoCamera /></el-icon>
                  {{ isRecording ? '录制中...' : '开始录制' }}
                </el-button>
                <el-button 
                  v-if="isRecording" 
                  @click="stopSelfIntroduction"
                  type="danger"
                  size="large"
                >
                  停止录制
                </el-button>
              </div>
              
              <div class="recording-timer" v-if="isRecording">
                <el-icon><Clock /></el-icon>
                <span>{{ formatTime(recordingTime) }} / 00:30</span>
              </div>
              
              <div v-if="selfIntroductionVideo" class="video-preview">
                <video :src="selfIntroductionVideo" controls width="400"></video>
                <div class="video-actions">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="retakeVideo"
                  >
                    重新录制
                  </el-button>
                  <el-button 
                    type="success" 
                    size="small" 
                    @click="confirmSelfIntroVideo"
                  >
                    确认使用
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 逻辑能力阶段 -->
      <div v-else-if="currentStage.id === 'logic' && !isInterviewLocked" class="logic-stage">
        <div class="stage-header">
          <h2>逻辑思维测试</h2>
          <div class="timer">
            <el-icon><Clock /></el-icon>
            <span>{{ formatTime(timeRemaining) }}</span>
          </div>
        </div>
        
        <div v-if="skipSections.logic" class="skip-section">
          <el-alert title="跳过逻辑思维测试部分" type="info" :closable="false" />
        </div>
        
        <div v-else-if="logicQuestions.length === 0" class="loading-section">
          <el-skeleton :rows="4" animated />
          <p>正在加载题目...</p>
        </div>
        
        <div v-else-if="currentQuestion && currentQuestion.title" class="question-section">
          <div class="question-counter">
            <span>第 {{ currentQuestionIndex + 1 }} / {{ logicQuestions.length }} 题</span>
          </div>
          
          <div class="question-content">
            <div class="question-header">
            <h3>{{ currentQuestion.title }}</h3>
              <div class="question-actions">
                <el-button 
                  v-if="currentQuestion.audio_url"
                  type="info" 
                  size="small" 
                  @click="playQuestionAudio"
                  :loading="isPlayingAudio"
                >
                  <el-icon><VideoPlay /></el-icon>
                  {{ isPlayingAudio ? '播放中...' : '播放题目' }}
                </el-button>
                <el-button 
                  v-if="availableVoiceProfiles.length > 0"
                  type="primary" 
                  size="small" 
                  @click="showVoiceSelector = true"
                >
                  <el-icon><Microphone /></el-icon>
                  切换语音
                </el-button>
              </div>
            </div>
            <p class="question-text">{{ currentQuestion.content }}</p>
            
            <!-- 选择题 -->
            <div v-if="currentQuestion.type === 'multipleChoice' && currentQuestion.options" class="multiple-choice">
              <el-radio-group v-model="logicAnswers[currentQuestion.id]">
                <el-radio 
                  v-for="(option, index) in currentQuestion.options" 
                  :key="index"
                  :label="option"
                  class="option-radio"
                >
                  {{ option }}
                </el-radio>
              </el-radio-group>
            </div>
            
            <!-- 填空题 -->
            <div v-else-if="currentQuestion.type === 'fillBlank'" class="fill-blank">
              <el-input 
                v-model="logicAnswers[currentQuestion.id]"
                type="textarea"
                :rows="4"
                placeholder="请输入您的答案..."
              />
            </div>
          </div>
          
          <div class="question-navigation">
            <el-button 
              @click="previousQuestion" 
              :disabled="currentQuestionIndex === 0"
            >
              上一题
            </el-button>
            <el-button 
              type="primary" 
              @click="nextQuestion"
            >
              {{ currentQuestionIndex === logicQuestions.length - 1 ? '提交答案' : '下一题' }}
            </el-button>
          </div>
        </div>
        
        <div v-else class="error-section">
          <el-alert title="题目加载失败" type="error" :closable="false">
            <p>无法加载逻辑题目，请刷新页面重试</p>
          </el-alert>
        </div>
      </div>
      
      <!-- 创新类题目阶段 -->
      <div v-else-if="currentStage.id === 'innovation' && !isInterviewLocked" class="innovation-stage">
        <div class="stage-header">
          <h2>创新能力评测</h2>
          <div class="timer">
            <el-icon><Clock /></el-icon>
            <span>{{ formatTime(timeRemaining) }}</span>
          </div>
        </div>
        
        <div v-if="skipSections.innovation" class="skip-section">
          <el-alert title="跳过创新思考类题目" type="info" :closable="false" />
        </div>
        
        <div v-else class="multi-round-questions">
          <div v-for="(question, index) in innovationQuestions" :key="question.id" class="question-round">
            <div class="round-header">
              <h3>第 {{ index + 1 }} 轮问题</h3>
              <el-tag type="primary">{{ question.category_display }}</el-tag>
              <span class="duration-info">建议时长：{{ Math.floor(question.answer_duration / 60) }}分钟</span>
            </div>
            
            <div class="question-content">
              <div class="question-header">
              <h4>{{ question.title }}</h4>
                <div class="question-actions">
                  <el-button 
                    v-if="question.audio_url"
                    type="info" 
                    size="small" 
                    @click="playQuestionAudio(question)"
                    :loading="isPlayingAudio"
                  >
                    <el-icon><VideoPlay /></el-icon>
                    {{ isPlayingAudio ? '播放中...' : '播放题目' }}
                  </el-button>
                  <el-button 
                    v-if="availableVoiceProfiles.length > 0"
                    type="primary" 
                    size="small" 
                    @click="showVoiceSelector = true"
                  >
                    <el-icon><Microphone /></el-icon>
                    切换语音
                  </el-button>
                </div>
              </div>
              <p class="question-text">{{ question.content }}</p>
              
              <div v-if="question.excellent_answer_example" class="example-section">
                <h5>优秀回答示例：</h5>
                <p class="example-text">{{ question.excellent_answer_example }}</p>
              </div>
              
              <div v-if="question.scoring_criteria" class="criteria-section">
                <h5>评分标准：</h5>
                <div class="criteria-text" v-html="question.scoring_criteria.replace(/\n/g, '<br>')"></div>
              </div>
              
              <div class="answer-section">
                <div class="recording-area">
                  <div class="recording-controls">
                    <el-button 
                      type="primary" 
                      @click="startVideoRecording(question.id)"
                      :disabled="recordings[question.id]?.isRecording"
                    >
                      <el-icon><VideoCamera /></el-icon>
                      {{ recordings[question.id]?.isRecording ? '录制中...' : '开始录制' }}
                    </el-button>
                    <el-button 
                      v-if="recordings[question.id]?.isRecording"
                      type="danger" 
                      @click="stopVideoRecording(question.id)"
                    >
                      <el-icon><VideoPause /></el-icon>
                      停止录制
                    </el-button>
                    <el-button 
                      @click="startAudioRecording(question.id)"
                      :disabled="audioRecordings[question.id]?.isRecording"
                    >
                      <el-icon><Microphone /></el-icon>
                      {{ audioRecordings[question.id]?.isRecording ? '录音中...' : '语音回答' }}
                    </el-button>
                  </div>
                  
                  <div v-if="recordings[question.id]?.url" class="video-preview">
                    <video :src="recordings[question.id].url" controls width="300"></video>
                    <div class="video-actions">
                      <el-button 
                        type="primary" 
                        size="small" 
                        @click="retakeVideoRecording(question.id)"
                      >
                        重新录制
                      </el-button>
                      <el-button 
                        type="success" 
                        size="small" 
                        @click="confirmVideoRecording(question.id)"
                        :loading="videoUploadStatus[question.id]?.uploading"
                      >
                        {{ videoUploadStatus[question.id]?.uploading ? '上传中...' : '确认使用' }}
                      </el-button>
                    </div>
                  </div>
                  
                  <!-- 视频上传状态指示器 -->
                  <div v-if="videoUploadStatus[question.id]" class="upload-status">
                    <div v-if="videoUploadStatus[question.id].uploading" class="status-item uploading">
                      <el-icon class="is-loading"><Loading /></el-icon>
                      <span>视频上传中...</span>
                    </div>
                    <div v-else-if="videoUploadStatus[question.id].analyzing" class="status-item analyzing">
                      <el-icon class="is-loading"><Loading /></el-icon>
                      <span>AI分析中...</span>
                    </div>
                    <div v-else-if="videoUploadStatus[question.id].completed" class="status-item completed">
                      <el-icon><Check /></el-icon>
                      <span>分析完成</span>
                    </div>
                    <div v-else-if="videoUploadStatus[question.id].error" class="status-item error">
                      <el-icon><Close /></el-icon>
                      <span>上传失败</span>
                    </div>
                  </div>
                  
                  <!-- AI分析结果展示 -->
                  <div v-if="aiAnalysisResults[question.id]" class="ai-analysis-results">
                    <div class="analysis-header">
                      <h4>AI分析结果</h4>
                      <el-tag type="success" size="small">{{ aiAnalysisResults[question.id].category }}</el-tag>
                    </div>
                    
                    <div class="scores-grid">
                      <div v-if="aiAnalysisResults[question.id].scores.expression_score" class="score-item">
                        <div class="score-label">表达能力</div>
                        <div class="score-value">{{ aiAnalysisResults[question.id].scores.expression_score }}</div>
                        <el-progress 
                          :percentage="aiAnalysisResults[question.id].scores.expression_score" 
                          :stroke-width="4"
                          :show-text="false"
                        />
                      </div>
                      <div v-if="aiAnalysisResults[question.id].scores.innovation_score" class="score-item">
                        <div class="score-label">创新能力</div>
                        <div class="score-value">{{ aiAnalysisResults[question.id].scores.innovation_score }}</div>
                        <el-progress 
                          :percentage="aiAnalysisResults[question.id].scores.innovation_score" 
                          :stroke-width="4"
                          :show-text="false"
                        />
                      </div>
                      <div v-if="aiAnalysisResults[question.id].scores.professional_skill_score" class="score-item">
                        <div class="score-label">专业技能</div>
                        <div class="score-value">{{ aiAnalysisResults[question.id].scores.professional_skill_score }}</div>
                        <el-progress 
                          :percentage="aiAnalysisResults[question.id].scores.professional_skill_score" 
                          :stroke-width="4"
                          :show-text="false"
                        />
                      </div>
                      <div v-if="aiAnalysisResults[question.id].scores.stress_management_score" class="score-item">
                        <div class="score-label">压力应对</div>
                        <div class="score-value">{{ aiAnalysisResults[question.id].scores.stress_management_score }}</div>
                        <el-progress 
                          :percentage="aiAnalysisResults[question.id].scores.stress_management_score" 
                          :stroke-width="4"
                          :show-text="false"
                        />
                      </div>
                    </div>
                    
                    <div class="analysis-message">
                      <el-icon><InfoFilled /></el-icon>
                      <span>{{ aiAnalysisResults[question.id].message }}</span>
                    </div>
                  </div>

                  <!-- 面部表情分析组件 -->
                  <div v-if="recordings[question.id]?.blob" class="expression-analysis-section">
                    <h4>面部表情分析</h4>
                    <ExpressionAnalysis
                      :video-file="recordings[question.id].blob"
                      :auto-analyze="true"
                      @analysis-complete="onExpressionAnalysisComplete(question.id, $event)"
                      @analysis-error="onExpressionAnalysisError(question.id, $event)"
                    />
                  </div>
                  
                  <div v-if="audioRecordings[question.id]?.url" class="audio-preview">
                    <audio :src="audioRecordings[question.id].url" controls></audio>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 专业技能类题目阶段 -->
      <div v-else-if="currentStage.id === 'professional' && !isInterviewLocked" class="professional-stage">
        <div class="stage-header">
          <h2>专业技能评测</h2>
          <div class="timer">
            <el-icon><Clock /></el-icon>
            <span>{{ formatTime(timeRemaining) }}</span>
          </div>
        </div>
        
        <div v-if="skipSections.professional" class="skip-section">
          <el-alert title="跳过专业技能类题目" type="info" :closable="false" />
        </div>
        
        <div v-else class="skill-questions">
          <div v-for="(question, index) in professionalQuestions" :key="question.id" class="skill-question">
            <div class="question-header">
              <h3>专业技能问题 {{ index + 1 }}</h3>
              <div class="skill-tags">
                <el-tag v-for="skill in (question.topic_tags ? question.topic_tags.split(',') : [])" :key="skill" size="small">
                  {{ skill.trim() }}
                </el-tag>
              </div>
              <span class="duration-info">建议时长：{{ Math.floor(question.answer_duration / 60) }}分钟</span>
            </div>
            
            <div class="question-content">
              <h4>{{ question.title }}</h4>
              <p class="question-text">{{ question.content }}</p>
              
              <div v-if="question.excellent_answer_example" class="example-section">
                <h5>优秀回答示例：</h5>
                <p class="example-text">{{ question.excellent_answer_example }}</p>
              </div>
              
              <div v-if="question.scoring_criteria" class="criteria-section">
                <h5>评分标准：</h5>
                <div class="criteria-text" v-html="question.scoring_criteria.replace(/\n/g, '<br>')"></div>
              </div>
              
              <div class="answer-section">
                <div class="recording-area">
                  <div class="recording-controls">
                    <el-button 
                      type="primary" 
                      @click="startVideoRecording(question.id)"
                      :disabled="recordings[question.id]?.isRecording"
                    >
                      <el-icon><VideoCamera /></el-icon>
                      {{ recordings[question.id]?.isRecording ? '录制中...' : '开始录制' }}
                    </el-button>
                    <el-button 
                      v-if="recordings[question.id]?.isRecording"
                      type="danger" 
                      @click="stopVideoRecording(question.id)"
                    >
                      <el-icon><VideoPause /></el-icon>
                      停止录制
                    </el-button>
                    <el-button 
                      @click="startAudioRecording(question.id)"
                      :disabled="audioRecordings[question.id]?.isRecording"
                    >
                      <el-icon><Microphone /></el-icon>
                      {{ audioRecordings[question.id]?.isRecording ? '录音中...' : '语音回答' }}
                    </el-button>
                  </div>
                  
                  <div v-if="recordings[question.id]?.url" class="video-preview">
                    <video :src="recordings[question.id].url" controls width="300"></video>
                    <div class="video-actions">
                      <el-button 
                        type="primary" 
                        size="small" 
                        @click="retakeVideoRecording(question.id)"
                      >
                        重新录制
                      </el-button>
                      <el-button 
                        type="success" 
                        size="small" 
                        @click="confirmVideoRecording(question.id)"
                      >
                        确认使用
                      </el-button>
                    </div>
                  </div>
                  
                  <div v-if="audioRecordings[question.id]?.url" class="audio-preview">
                    <audio :src="audioRecordings[question.id].url" controls></audio>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 压力应对阶段 -->
      <div v-else-if="currentStage.id === 'pressure' && !isInterviewLocked" class="pressure-stage">
        <div class="stage-header">
          <h2>压力应对测试</h2>
          <div class="pressure-indicator">
            <span class="pressure-label">压力等级</span>
            <el-progress 
              :percentage="pressureLevel" 
              :stroke-width="8"
              color="#ff6b6b"
            />
          </div>
        </div>
        
        <div class="pressure-scenario">
          <div class="scenario-description">
            <h3>压力场景</h3>
            <p>{{ currentPressureScenario.description }}</p>
          </div>
          
          <div v-if="skipSections.pressure" class="skip-section">
            <el-alert title="跳过压力应对类题目" type="info" :closable="false" />
          </div>
          
          <div v-else class="pressure-questions">
            <div v-for="(question, index) in pressureQuestions" :key="question.id" class="pressure-question">
              <div class="question-header">
                <h4>{{ question.title }}</h4>
                <el-tag type="warning">{{ question.category_display }}</el-tag>
                <span class="duration-info">建议时长：{{ Math.floor(question.answer_duration / 60) }}分钟</span>
              </div>
              
              <div class="question-content">
                <p class="question-text">{{ question.content }}</p>
                
                <div v-if="question.excellent_answer_example" class="example-section">
                  <h5>优秀回答示例：</h5>
                  <p class="example-text">{{ question.excellent_answer_example }}</p>
                </div>
                
                <div v-if="question.scoring_criteria" class="criteria-section">
                  <h5>评分标准：</h5>
                  <div class="criteria-text" v-html="question.scoring_criteria.replace(/\n/g, '<br>')"></div>
                </div>
                
                <div class="answer-section">
                  <div class="recording-area">
                    <div class="recording-controls">
                      <el-button 
                        type="primary" 
                        @click="startVideoRecording(question.id)"
                        :disabled="recordings[question.id]?.isRecording"
                      >
                        <el-icon><VideoCamera /></el-icon>
                        {{ recordings[question.id]?.isRecording ? '录制中...' : '开始录制' }}
                      </el-button>
                      <el-button 
                        v-if="recordings[question.id]?.isRecording"
                        type="danger" 
                        @click="stopVideoRecording(question.id)"
                      >
                        <el-icon><VideoPause /></el-icon>
                        停止录制
                      </el-button>
                      <el-button 
                        @click="startAudioRecording(question.id)"
                        :disabled="audioRecordings[question.id]?.isRecording"
                      >
                        <el-icon><Microphone /></el-icon>
                        {{ audioRecordings[question.id]?.isRecording ? '录音中...' : '语音回答' }}
                      </el-button>
                    </div>
                    
                    <div v-if="recordings[question.id]?.url" class="video-preview">
                      <video :src="recordings[question.id].url" controls width="300"></video>
                      <div class="video-actions">
                        <el-button 
                          type="primary" 
                          size="small" 
                          @click="retakeVideoRecording(question.id)"
                        >
                          重新录制
                        </el-button>
                        <el-button 
                          type="success" 
                          size="small" 
                          @click="confirmVideoRecording(question.id)"
                        >
                          确认使用
                        </el-button>
                      </div>
                    </div>
                    
                    <div v-if="audioRecordings[question.id]?.url" class="audio-preview">
                      <audio :src="audioRecordings[question.id].url" controls></audio>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 底部进度条和操作按钮 -->
    <div class="stage-footer">
      <div class="progress-info">
        <span>总体进度：{{ Math.round(overallProgress) }}%</span>
        <el-progress 
          :percentage="overallProgress" 
          :stroke-width="6"
          color="#6753C0"
        />
      </div>
      
      <div class="footer-actions">
        <el-button 
          @click="previousStage" 
          :disabled="currentStageIndex === 0"
        >
          上一阶段
        </el-button>
        <el-button 
          type="primary" 
          @click="nextStage"
          :disabled="false"
        >
          {{ currentStageIndex === stages.length - 1 ? '完成面试' : '下一阶段' }}
        </el-button>
      </div>
    </div>

    <!-- 语音选择器对话框 -->
    <el-dialog
      v-model="showVoiceSelector"
      title="选择语音配置"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="voice-selector">
        <div class="voice-profiles-grid">
          <div
            v-for="profile in availableVoiceProfiles"
            :key="profile.id"
            class="voice-profile-card"
            :class="{ 'is-selected': selectedVoiceProfile === profile.id }"
            @click="selectVoiceProfile(profile)"
          >
            <div class="voice-profile-header">
              <span class="voice-type">{{ profile.voice_type }}</span>
              <el-tag :type="profile.is_active ? 'success' : 'info'" size="small">
                {{ profile.is_active ? '可用' : '不可用' }}
              </el-tag>
            </div>
            <div class="voice-profile-content">
              <h5>{{ profile.name }}</h5>
              <p>{{ profile.description }}</p>
              <div class="voice-params">
                <span>语速: {{ profile.speed }}x</span>
                <span>音调: {{ profile.pitch }}x</span>
                <span>音量: {{ profile.volume }}x</span>
              </div>
            </div>
            <div class="voice-profile-actions">
              <el-button
                v-if="profile.is_active"
                size="small"
                @click.stop="testVoice(profile)"
                :loading="testingVoice === profile.id"
              >
                试听
              </el-button>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showVoiceSelector = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmVoiceSelection"
            :disabled="!selectedVoiceProfile"
          >
            确认选择
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import { Clock, VideoCamera, Microphone, VideoPause, Loading, Check, Close, InfoFilled, VideoPlay } from '@element-plus/icons-vue'
import { interviewApi, sparkApi } from '@/services/api'
import ExpressionAnalysis from '@/components/ExpressionAnalysis.vue'

export default {
  name: 'InterviewSessionView',
  components: {
    Clock,
    VideoCamera,
    Microphone,
    VideoPause,
    Loading,
    Check,
    Close,
    InfoFilled,
    VideoPlay,
    ExpressionAnalysis
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    
    // 从路由参数获取applicationId，支持多种参数名称
    const applicationId = route.params.applicationId || route.query.applicationId || route.query.id
    
    // 响应式数据
    const currentStageIndex = ref(0)
    const currentQuestionIndex = ref(0)
    const isRecording = ref(false)
    const recordingTime = ref(0)
    const timeRemaining = ref(0)
    const pressureLevel = ref(0)
    const selfIntroductionVideo = ref(null)
    const loading = ref(false)
    const isCameraPreviewOn = ref(false)
    const previewVideo = ref(null)
    const showAnalysisResults = ref(false)
    const analysisLoading = ref(false)
    const aiAnalysisResults = reactive({})
    const videoUploadStatus = reactive({})
    
    const answers = reactive({})
    const recordings = reactive({})
    const audioRecordings = reactive({})
    const logicAnswers = reactive({})
    // videoAnswers已移除，现在视频在确认时直接上传
    const uploadedVideoUrls = reactive({}) // 存储已上传的视频URL
    
    // 语音相关变量
    const showVoiceSelector = ref(false)
    const selectedVoiceProfile = ref(null)
    const availableVoiceProfiles = ref([])
    const isPlayingAudio = ref(false)
    const testingVoice = ref(null)
    const currentAudio = ref(null)
    
    // 面试状态相关
    const interviewStatus = ref('pending') // pending, logic_test, video_interview, generating_report, completed
    const isInterviewLocked = ref(false) // 面试是否被锁定
    const interviewProgress = reactive({
      total_video_questions: 0,
      answered_video_questions: 0,
      percentage: 0
    })
    const statusMessage = ref('')
    const statusCheckTimer = ref(null)
    
    // 面试信息
    const interview = reactive({
      company: '',
      position: '',
      title: '面试进行中', // 添加默认标题
      status: 'pending'    // 添加默认状态
    })
    
    // 候选人信息
    const candidateInfo = reactive({
      name: '',
      email: '',
      phone: '',
      experience: '',
      education: '',
      skills: [],
      resume_url: '',
      parsed_content: ''
    })
    
    // 阶段配置
    const stages = ref([
      {
        id: 'resume',
        name: '简历匹配',
        description: '简历信息确认',
        icon: 'Document',
        timeLimit: 300 // 5分钟
      },
      {
        id: 'logic',
        name: '逻辑能力',
        description: '逻辑思维测试',
        icon: 'Brain',
        timeLimit: 1800 // 30分钟
      },
      {
        id: 'innovation',
        name: '创新能力',
        description: '创新思维评测',
        icon: 'Lightbulb',
        timeLimit: 2700 // 45分钟
      },
      {
        id: 'professional',
        name: '专业技能',
        description: '专业技能评测',
        icon: 'Tools',
        timeLimit: 3600 // 60分钟
      },
      {
        id: 'pressure',
        name: '压力应对',
        description: '压力应对测试',
        icon: 'Warning',
        timeLimit: 1800 // 30分钟
      }
    ])
    
    // 题目数据
    const logicQuestions = ref([])
    const innovationQuestions = ref([])
    const professionalQuestions = ref([])
    const pressureQuestions = ref([])
    
    // 跳过标记
    const skipSections = reactive({
      logic: false,
      innovation: false,
      professional: false,
      pressure: false
    })
    
    // 压力应对场景
    const currentPressureScenario = reactive({
      description: '项目即将上线，但发现了严重的性能问题，客户要求必须按时交付，团队成员情绪低落。',
      questions: [
        {
          id: 'pressure_1',
          content: '在这种情况下，你会如何安排工作优先级？',
          intensity: 3
        },
        {
          id: 'pressure_2',
          content: '如何与客户沟通可能的延期风险？',
          intensity: 4
        },
        {
          id: 'pressure_3',
          content: '团队士气低落时，你会采取什么措施？',
          intensity: 5
        }
      ]
    })
    
    // 计算属性
    const currentStage = computed(() => stages.value[currentStageIndex.value])
    const progressPercentage = computed(() => ((currentStageIndex.value + 1) / stages.value.length) * 100)
    const overallProgress = computed(() => {
      // 根据各阶段完成情况计算总体进度
      let totalProgress = 0
      stages.value.forEach((stage, index) => {
        if (index < currentStageIndex.value) {
          totalProgress += 100 / stages.value.length
        } else if (index === currentStageIndex.value) {
          // 当前阶段的进度（简化计算）
          totalProgress += (50 / stages.value.length) // 假设当前阶段完成50%
        }
      })
      return totalProgress
    })
    
    const currentQuestion = computed(() => {
      if (currentStage.value.id === 'logic' && logicQuestions.value.length > 0) {
        return logicQuestions.value[currentQuestionIndex.value] || {}
      }
      return {}
    })
    
    // API调用方法
    const loadResumeInfo = async () => {
      if (!applicationId) {
        ElMessage.error('缺少申请ID参数')
        return
      }
      
      try {
        loading.value = true
        const response = await interviewApi.getResumeInfo(applicationId)
        
        if (response.success) {
          Object.assign(candidateInfo, response.data)
          // 从简历信息推断面试信息（如果有的话）
          // interview.company = response.data.company || ''
          // interview.position = response.data.position || ''
        }
      } catch (error) {
        console.error('获取简历信息失败:', error)
        ElMessage.error('获取简历信息失败')
      } finally {
        loading.value = false
      }
    }

    const loadLogicQuestions = async () => {
      if (!applicationId) return
      
      try {
        const response = await interviewApi.getLogicQuestions(applicationId)
        
        console.log('逻辑题API响应:', response) // 调试信息
        
        if (response.success) {
          if (response.data.skip_section) {
            skipSections.logic = true
            ElMessage.info('跳过逻辑思维测试部分')
          } else {
            logicQuestions.value = response.data.questions.map(q => {
              console.log('处理题目:', q) // 调试信息
              
              // 更灵活的类型判断
              const isMultipleChoice = q.question_type === 'single_choice' || 
                                     q.question_type === 'multiple_choice' ||
                                     (q.options && q.options.length > 0)
              
              return {
                id: q.id,
                title: q.title || '题目标题',
                content: q.content || '题目内容',
                type: isMultipleChoice ? 'multipleChoice' : 'fillBlank',
                options: q.options ? q.options.map(opt => opt.text || opt) : [],
                optionIds: q.options ? q.options.map(opt => opt.id || opt) : []
              }
            })
            
            console.log('处理后的逻辑题:', logicQuestions.value) // 调试信息
          }
        } else {
          console.error('逻辑题API返回失败:', response)
          ElMessage.error('获取逻辑题目失败')
        }
      } catch (error) {
        console.error('获取逻辑题目失败:', error)
        ElMessage.error('获取逻辑题目失败')
      }
    }

    const loadVideoQuestions = async (category) => {
      if (!applicationId) return
      
      try {
        const response = await interviewApi.getVideoQuestions(applicationId, category)
        
        if (response.success) {
          if (response.data.skip_section) {
            skipSections[category] = true
            ElMessage.info(`跳过${response.data.category_display}部分`)
          } else {
            const questions = response.data.questions.map(q => ({
              id: q.id,
              title: q.title,
              content: q.content,
              category: q.category,
              category_display: q.category_display,
              answer_duration: q.answer_duration,
              excellent_answer_example: q.excellent_answer_example,
              scoring_criteria: q.scoring_criteria,
              topic_tags: q.topic_tags
            }))
            
            if (category === 'innovation') {
              innovationQuestions.value = questions
            } else if (category === 'professional') {
              professionalQuestions.value = questions
            } else if (category === 'pressure') {
              pressureQuestions.value = questions
            }
          }
        }
      } catch (error) {
        console.error(`获取${category}题目失败:`, error)
        ElMessage.error(`获取${category}题目失败`)
      }
    }

    const submitSelfIntroduction = async (videoFile) => {
      if (!applicationId || !videoFile) {
        console.error('缺少必要参数:', { applicationId, videoFile })
        return
      }
      
      try {
        console.log('开始上传自我介绍视频:', {
          applicationId,
          videoFile: {
            name: videoFile.name,
            size: videoFile.size,
            type: videoFile.type
          }
        })
        
        const response = await interviewApi.uploadSelfIntroduction(applicationId, videoFile)
        
        console.log('自我介绍视频上传响应:', response)
        
        if (response.success) {
          ElMessage.success('自我介绍视频上传成功')
          // 处理后端返回的视频URL（如果需要）
          if (response.data && response.data.video_url) {
            console.log('视频已上传到:', response.data.video_url)
            uploadedVideoUrls['self-introduction'] = response.data.video_url
          }
        } else {
          console.error('自我介绍视频上传失败:', response)
          ElMessage.error(`自我介绍视频上传失败: ${response.message || '未知错误'}`)
        }
      } catch (error) {
        console.error('上传自我介绍失败:', error)
        console.error('错误详情:', {
          message: error.message,
          response: error.response?.data,
          status: error.response?.status
        })
        ElMessage.error(`上传自我介绍失败: ${error.message || '网络错误'}`)
      }
    }

    const submitLogicAnswers = async () => {
      if (!applicationId || Object.keys(logicAnswers).length === 0) return
      
      try {
        const answers = Object.entries(logicAnswers).map(([questionId, answer]) => {
          const question = logicQuestions.value.find(q => q.id == questionId)
          if (question && question.type === 'multipleChoice') {
            // 找到选项对应的ID
            const optionIndex = question.options.indexOf(answer)
            const optionId = question.optionIds[optionIndex]
            return {
              question_id: parseInt(questionId),
              selected_option_id: optionId
            }
          } else {
            return {
              question_id: parseInt(questionId),
              answer: answer
            }
          }
        })

        const response = await interviewApi.submitLogicAnswers(applicationId, answers)
        
        if (response.success) {
          ElMessage.success('逻辑测试答案已提交')
        }
      } catch (error) {
        console.error('提交逻辑答案失败:', error)
        ElMessage.error('提交逻辑答案失败')
      }
    }

    // 修改：使用星火大模型API提交视频答案
    const submitVideoAnswer = async (category, questionId, videoFile) => {
      try {
        console.log('提交视频答案到星火大模型API:', {
          applicationId,
          category,
          questionId,
          videoFile: {
            name: videoFile.name,
            size: videoFile.size,
            type: videoFile.type
          }
        })
        
        // 设置上传状态
        videoUploadStatus[questionId] = {
          uploading: true,
          analyzing: false,
          completed: false,
          error: false
        }
        
        const response = await sparkApi.submitVideoAnswerWithAnalysis(applicationId, category, questionId, videoFile)
        console.log('星火大模型API响应:', response)
        
        if (response.success) {
          // 更新上传状态
          videoUploadStatus[questionId] = {
            uploading: false,
            analyzing: true,
            completed: false,
            error: false
          }
          
          // 保存AI分析结果
          const processedAnswer = response.data.processed_answers[0]
          if (processedAnswer) {
            aiAnalysisResults[questionId] = {
              video_url: processedAnswer.video_url,
              scores: processedAnswer.scores,
              category: response.data.category,
              message: response.data.message
            }
            
            // 显示分析结果
            showAnalysisResults.value = true
            
            // 更新状态为完成
            videoUploadStatus[questionId] = {
              uploading: false,
              analyzing: false,
              completed: true,
              error: false
            }
            
            ElMessage.success(`视频上传成功，AI分析完成`)
          }
        } else {
          throw new Error(response.message || '上传失败')
        }
        
      } catch (error) {
        console.error(`提交${category}答案失败:`, error)
        console.error('错误详情:', {
          message: error.message,
          response: error.response?.data,
          status: error.response?.status
        })
        
        // 更新上传状态为错误
        videoUploadStatus[questionId] = {
          uploading: false,
          analyzing: false,
          completed: false,
          error: true
        }
        
        ElMessage.error(`提交${category}答案失败: ${error.message || '网络错误'}`)
      }
    }
    
    // 方法
    const formatTime = (seconds) => {
      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = seconds % 60
      return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
    }
    
    // 处理后端返回的视频URL
    const getVideoUrl = (videoPath) => {
      if (!videoPath) return null
      if (videoPath.startsWith('http')) {
        return videoPath // 已经是完整URL
      }
      return `http://127.0.0.1:8000${videoPath}` // 拼接后端域名
    }
    
    const startTimer = () => {
      timeRemaining.value = currentStage.value.timeLimit
      const timer = setInterval(() => {
        timeRemaining.value--
        if (timeRemaining.value <= 0) {
          clearInterval(timer)
          // 时间到，自动进入下一阶段
          nextStage()
        }
      }, 1000)
    }
    
    const startSelfIntroduction = async () => {
      try {
        // 获取摄像头权限
        const stream = await navigator.mediaDevices.getUserMedia({ 
          video: true, 
          audio: true 
        })
        
        // 创建MediaRecorder
        const mediaRecorder = new MediaRecorder(stream)
        const chunks = []
        
        mediaRecorder.ondataavailable = (event) => {
          if (event.data.size > 0) {
            chunks.push(event.data)
          }
        }
        
        mediaRecorder.onstop = () => {
          const blob = new Blob(chunks, { type: 'video/webm' })
          const videoUrl = URL.createObjectURL(blob)
          selfIntroductionVideo.value = videoUrl
          
          // 保存视频文件对象，用于后续上传
          window.selfIntroductionVideoFile = blob
          
          // 停止所有轨道
          stream.getTracks().forEach(track => track.stop())
        }
        
        isRecording.value = true
        recordingTime.value = 0
        mediaRecorder.start()
        
        // 开始计时
        const timer = setInterval(() => {
          recordingTime.value++
          if (recordingTime.value >= 30) {
            clearInterval(timer)
            mediaRecorder.stop()
            isRecording.value = false
          }
        }, 1000)
        
        // 保存定时器引用以便手动停止
        window.currentRecordingTimer = timer
        window.currentMediaRecorder = mediaRecorder
        
      } catch (error) {
        console.error('无法访问摄像头:', error)
        ElMessage.error('无法访问摄像头，请检查权限设置')
      }
    }
    
    const stopSelfIntroduction = () => {
      if (window.currentMediaRecorder && window.currentMediaRecorder.state === 'recording') {
        window.currentMediaRecorder.stop()
      }
      if (window.currentRecordingTimer) {
        clearInterval(window.currentRecordingTimer)
      }
      isRecording.value = false
    }
    
    const retakeVideo = () => {
      selfIntroductionVideo.value = null
      recordingTime.value = 0
      // 清除保存的视频文件对象
      window.selfIntroductionVideoFile = null
    }

    const confirmSelfIntroVideo = async () => {
      if (selfIntroductionVideo.value && window.selfIntroductionVideoFile) {
        try {
          // 创建有意义的文件名
          const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
          const candidateName = candidateInfo.name || 'candidate'
          const fileName = `self_intro_${candidateName}_${timestamp}.mp4`
          
          // 创建File对象，而不是直接传递blob
          const videoFile = new File([window.selfIntroductionVideoFile], fileName, {
            type: 'video/mp4'
          })
          
          console.log('创建的文件对象:', {
            name: videoFile.name,
            size: videoFile.size,
            type: videoFile.type,
            isFile: videoFile instanceof File
          })
          
          await submitSelfIntroduction(videoFile)
          ElMessage.success('自我介绍视频已确认使用')
        } catch (error) {
          console.error('创建视频文件失败:', error)
          ElMessage.error('视频文件处理失败')
        }
      } else {
        ElMessage.warning('请先录制视频')
      }
    }
    
    const startCameraPreview = async () => {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ 
          video: true, 
          audio: false 
        })
        
        if (previewVideo.value) {
          previewVideo.value.srcObject = stream
          isCameraPreviewOn.value = true
        }
      } catch (error) {
        console.error('无法访问摄像头:', error)
        ElMessage.error('无法访问摄像头，请检查权限设置')
      }
    }
    
    const stopCameraPreview = () => {
      if (previewVideo.value && previewVideo.value.srcObject) {
        const stream = previewVideo.value.srcObject
        stream.getTracks().forEach(track => track.stop())
        previewVideo.value.srcObject = null
        isCameraPreviewOn.value = false
      }
    }
    
    const previousQuestion = () => {
      if (currentQuestionIndex.value > 0) {
        currentQuestionIndex.value--
      }
    }
    
    const nextQuestion = async () => {
      if (currentQuestionIndex.value < logicQuestions.value.length - 1) {
        currentQuestionIndex.value++
      } else {
        // 最后一题，提交答案并进入下一阶段
        try {
          await submitLogicAnswers()
          ElMessage.success('逻辑题答案已提交')
          // 自动进入下一阶段
          await nextStage()
        } catch (error) {
          console.error('提交逻辑答案失败:', error)
          ElMessage.error('提交失败，请重试')
        }
      }
    }
    
    const startVideoRecording = async (questionId) => {
      try {
        // 获取摄像头权限
        const stream = await navigator.mediaDevices.getUserMedia({ 
          video: true, 
          audio: true 
        })
        
        // 创建MediaRecorder
        const mediaRecorder = new MediaRecorder(stream)
        const chunks = []
        
        mediaRecorder.ondataavailable = (event) => {
          if (event.data.size > 0) {
            chunks.push(event.data)
          }
        }
        
        mediaRecorder.onstop = () => {
          const blob = new Blob(chunks, { type: 'video/webm' })
          const videoUrl = URL.createObjectURL(blob)
          
          // 更新录制状态
          recordings[questionId] = {
            isRecording: false,
            url: videoUrl,
            blob: blob,
            confirmed: false
          }
          
          // 停止所有轨道
          stream.getTracks().forEach(track => track.stop())
          
          ElMessage.success('视频录制完成')
        }
        
        // 设置录制状态
        recordings[questionId] = {
          isRecording: true,
          url: null,
          blob: null,
          confirmed: false
        }
        
        mediaRecorder.start()
        
        // 保存引用以便停止录制
        recordings[questionId].mediaRecorder = mediaRecorder
        recordings[questionId].stream = stream
        
      } catch (error) {
        console.error('无法访问摄像头:', error)
        ElMessage.error('无法访问摄像头，请检查权限设置')
        
        // 重置录制状态
        if (recordings[questionId]) {
          recordings[questionId].isRecording = false
          recordings[questionId].confirmed = false
        }
      }
    }
    
    const stopVideoRecording = (questionId) => {
      const recording = recordings[questionId]
      if (recording && recording.mediaRecorder && recording.mediaRecorder.state === 'recording') {
        recording.mediaRecorder.stop()
      }
    }

    const retakeVideoRecording = (questionId) => {
      const recording = recordings[questionId]
      if (recording && recording.stream) {
        recording.stream.getTracks().forEach(track => track.stop())
      }
      recordings[questionId] = {
        isRecording: false,
        url: null,
        blob: null,
        confirmed: false
      }
      ElMessage.info('视频已重新录制')
    }

    const confirmVideoRecording = async (questionId) => {
      console.log('确认视频录制，questionId:', questionId)
      const recording = recordings[questionId]
      console.log('录制状态:', recording)
      
      if (recording && recording.blob) {
        try {
          const currentCategory = getCurrentVideoCategory()
          console.log('当前视频类别:', currentCategory)
          
          if (currentCategory) {
            // 创建有意义的文件名
            const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
            const candidateName = candidateInfo.name || 'candidate'
            const fileName = `${currentCategory}_q${questionId}_${candidateName}_${timestamp}.mp4`
            
            // 创建File对象，而不是直接传递blob
            const videoFile = new File([recording.blob], fileName, {
              type: 'video/mp4'
            })
            
            console.log('创建的文件对象:', {
              name: videoFile.name,
              size: videoFile.size,
              type: videoFile.type,
              isFile: videoFile instanceof File,
              category: currentCategory,
              questionId: questionId
            })
            
            await submitVideoAnswer(currentCategory, questionId, videoFile)
            
            // 标记视频为已确认状态
            recordings[questionId].confirmed = true
            
            // 提交视频答案后检查面试状态
            await checkInterviewStatus()
            
            ElMessage.success('视频已确认使用')
          } else {
            ElMessage.error('无法确定当前阶段')
          }
        } catch (error) {
          console.error('创建视频文件失败:', error)
          ElMessage.error('视频文件处理失败')
        }
      } else {
        console.log('录制状态检查失败:', { recording, hasBlob: recording?.blob })
        ElMessage.warning('请先录制视频')
            }
    }

    // 状态检查相关函数
    // 修改：使用星火大模型API检查面试状态
    const checkInterviewStatus = async () => {
      try {
        const response = await sparkApi.checkInterviewStatus(applicationId)
        console.log('面试状态检查结果:', response)
        
        if (response.success) {
          const { has_session, status, is_locked, progress, scores, message } = response.data
          
          // 更新状态
          interviewStatus.value = status
          isInterviewLocked.value = is_locked
          statusMessage.value = message
          
          // 更新进度信息
          if (progress) {
            interviewProgress.total_video_questions = progress.total_video_questions
            interviewProgress.answered_video_questions = progress.answered_video_questions
            interviewProgress.percentage = progress.percentage
          }
          
          // 如果面试被锁定，显示完成状态
          if (is_locked) {
            showInterviewCompleted(message)
            clearStatusCheckTimer()
          }
          
          return response.data
        }
      } catch (error) {
        console.error('检查面试状态失败:', error)
        // 不显示错误消息，避免过度干扰用户
      }
    }

    // 新增：获取面试结果（使用星火大模型API）
    const getInterviewResults = async () => {
      try {
        const response = await sparkApi.getInterviewResults(applicationId)
        console.log('面试结果:', response)
        
        if (response.success) {
          return response.data
        }
      } catch (error) {
        console.error('获取面试结果失败:', error)
      }
    }
    
    // 新增：生成综合报告
    const generateReport = async () => {
      try {
        const response = await sparkApi.generateReport(applicationId)
        console.log('生成报告结果:', response)
        
        if (response.success) {
          ElMessage.success('综合报告生成成功')
          return response.data
        }
      } catch (error) {
        console.error('生成报告失败:', error)
        ElMessage.error('生成报告失败')
      }
    }

    const showInterviewCompleted = (message) => {
      ElMessage.success(message || '面试已完成')
      // 可以在这里添加界面锁定逻辑
    }

    const startStatusCheckTimer = () => {
      // 每30秒检查一次状态
      if (statusCheckTimer.value) {
        clearInterval(statusCheckTimer.value)
      }
      
      statusCheckTimer.value = setInterval(async () => {
        await checkInterviewStatus()
      }, 30000) // 30秒
    }

    const clearStatusCheckTimer = () => {
      if (statusCheckTimer.value) {
        clearInterval(statusCheckTimer.value)
        statusCheckTimer.value = null
      }
    }

    // 语音相关方法
    const loadVoiceProfiles = async () => {
      try {
        // TODO: 暂时注释掉voiceApi调用，等后端API就绪后恢复
        // const response = await voiceApi.getInterviewVoiceProfiles(applicationId)
        // availableVoiceProfiles.value = response.voice_profiles || response.data || []
        
        // 临时使用模拟数据
        availableVoiceProfiles.value = [
          { id: 1, name: '标准女声', language: 'zh-CN', is_active: true },
          { id: 2, name: '标准男声', language: 'zh-CN', is_active: true }
        ];
        
        if (availableVoiceProfiles.value.length > 0 && !selectedVoiceProfile.value) {
          // 默认选择第一个可用的语音配置
          const firstActive = availableVoiceProfiles.value.find(p => p.is_active)
          if (firstActive) {
            selectedVoiceProfile.value = firstActive.id
          }
        }
      } catch (error) {
        console.error('加载语音配置失败:', error)
        ElMessage.error('加载语音配置失败')
      }
    }

    const playQuestionAudio = async (question = null) => {
      const targetQuestion = question || currentQuestion.value
      if (!targetQuestion || !targetQuestion.audio_url) {
        ElMessage.warning('该题目暂无音频')
        return
      }

      try {
        isPlayingAudio.value = true
        
        // 停止当前播放的音频
        if (currentAudio.value) {
          currentAudio.value.pause()
          currentAudio.value = null
        }

        // 创建新的音频元素
        const audio = new Audio(targetQuestion.audio_url)
        currentAudio.value = audio
        
        audio.addEventListener('ended', () => {
          isPlayingAudio.value = false
          currentAudio.value = null
        })
        
        audio.addEventListener('error', () => {
          isPlayingAudio.value = false
          currentAudio.value = null
          ElMessage.error('音频播放失败')
        })
        
        await audio.play()
        ElMessage.success('开始播放题目音频')
        
      } catch (error) {
        console.error('播放音频失败:', error)
        isPlayingAudio.value = false
        currentAudio.value = null
        ElMessage.error('音频播放失败')
      }
    }

    const selectVoiceProfile = (profile) => {
      if (profile.is_active) {
        selectedVoiceProfile.value = profile.id
      }
    }

    const confirmVoiceSelection = async () => {
      if (!selectedVoiceProfile.value) {
        ElMessage.warning('请选择语音配置')
        return
      }

      try {
        // 这里可以调用API更新用户的语音偏好
        ElMessage.success('语音配置已更新')
        showVoiceSelector.value = false
      } catch (error) {
        console.error('更新语音配置失败:', error)
        ElMessage.error('更新语音配置失败')
      }
    }

    const testVoice = async (profile) => {
      if (!profile.is_active) {
        ElMessage.warning('该语音配置不可用')
        return
      }

      testingVoice.value = profile.id
      try {
        // 这里可以调用语音合成API进行测试
        ElMessage.info(`正在测试语音: ${profile.name}`)
        await new Promise(resolve => setTimeout(resolve, 2000))
        ElMessage.success(`语音测试完成: ${profile.name}`)
      } catch (error) {
        console.error('语音测试失败:', error)
        ElMessage.error('语音测试失败')
      } finally {
        testingVoice.value = null
      }
    }

    // 面部表情分析完成处理
    const onExpressionAnalysisComplete = (questionId, result) => {
      console.log('面部表情分析完成:', questionId, result)
      
      // 将表情分析结果合并到AI分析结果中
      if (!aiAnalysisResults[questionId]) {
        aiAnalysisResults[questionId] = {}
      }
      
      aiAnalysisResults[questionId].expression_analysis = result
      aiAnalysisResults[questionId].expression_avg_score = result.expression_avg_score
      
      ElMessage.success('面部表情分析完成')
    }

    // 面部表情分析错误处理
    const onExpressionAnalysisError = (questionId, error) => {
      console.error('面部表情分析失败:', questionId, error)
      ElMessage.error('面部表情分析失败，请重试')
    }

    const closeAllCameras = () => {
      console.log('关闭所有摄像头和录制状态')
      
      // 关闭摄像头预览
      if (previewVideo.value && previewVideo.value.srcObject) {
        const stream = previewVideo.value.srcObject
        stream.getTracks().forEach(track => track.stop())
        previewVideo.value.srcObject = null
        isCameraPreviewOn.value = false
      }
      
      // 关闭所有录制中的摄像头
      Object.keys(recordings).forEach(questionId => {
        const recording = recordings[questionId]
        if (recording && recording.isRecording) {
          if (recording.mediaRecorder && recording.mediaRecorder.state === 'recording') {
            recording.mediaRecorder.stop()
          }
          if (recording.stream) {
            recording.stream.getTracks().forEach(track => track.stop())
          }
          recording.isRecording = false
        }
      })
      
      // 关闭自我介绍录制
      if (isRecording.value) {
        stopSelfIntroduction()
      }
      
      // 关闭所有音频录制
      Object.keys(audioRecordings).forEach(questionId => {
        const audioRecording = audioRecordings[questionId]
        if (audioRecording && audioRecording.isRecording) {
          audioRecording.isRecording = false
        }
      })
      
      console.log('所有摄像头和录制状态已关闭')
    }
    
    const getCurrentVideoCategory = () => {
      const stage = currentStage.value.id
      console.log('当前阶段ID:', stage)
      if (['innovation', 'professional', 'pressure'].includes(stage)) {
        console.log('返回视频类别:', stage)
        return stage
      }
      console.log('无法确定视频类别')
      return null
    }
    
    const startAudioRecording = (questionId) => {
      audioRecordings[questionId] = {
        isRecording: true,
        url: null
      }
      
      // 模拟录制过程
      setTimeout(() => {
        audioRecordings[questionId].isRecording = false
        audioRecordings[questionId].url = 'blob:mock-audio-url'
      }, 3000)
    }
    
    const previousStage = () => {
      if (currentStageIndex.value > 0) {
        currentStageIndex.value--
        startTimer()
      }
    }
    
    const nextStage = async () => {
      try {
        const currentStageId = currentStage.value.id
        console.log('当前阶段:', currentStageId, '当前阶段索引:', currentStageIndex.value)
        
        // 在切换阶段前提交当前阶段的答案
        if (currentStageId === 'logic' && !skipSections.logic) {
          console.log('提交逻辑答案...')
          await submitLogicAnswers()
        } else if (['innovation', 'professional', 'pressure'].includes(currentStageId) && !skipSections[currentStageId]) {
          let currentQuestionList = []
          if (currentStageId === 'innovation') currentQuestionList = innovationQuestions.value
          if (currentStageId === 'professional') currentQuestionList = professionalQuestions.value
          if (currentStageId === 'pressure') currentQuestionList = pressureQuestions.value

          const unconfirmedVideos = currentQuestionList.filter(q => {
            const rec = recordings[q.id]
            return rec && rec.blob && rec.url && !rec.confirmed
          })
          if (unconfirmedVideos.length > 0) {
            ElMessage.warning('还有未确认的视频，请先确认所有视频')
            return
          }
        }
        
        if (currentStageIndex.value < stages.value.length - 1) {
          currentStageIndex.value++
          console.log('进入下一阶段，新阶段索引:', currentStageIndex.value)
          
          // 加载下一阶段的题目
          const nextStageId = currentStage.value.id
          console.log('下一阶段ID:', nextStageId)
          
          if (nextStageId === 'logic') {
            await loadLogicQuestions()
          } else if (['innovation', 'professional', 'pressure'].includes(nextStageId)) {
            await loadVideoQuestions(nextStageId)
          }
          
          startTimer()
        } else {
          // 完成面试，关闭所有摄像头
          console.log('面试完成，关闭所有摄像头')
          closeAllCameras()
          
          // 跳转到面试结果页面
          console.log('面试完成，跳转到结果页面')
          ElMessage.success('面试已完成！')
          
          try {
            await router.push(`/candidate/interview-result?applicationId=${applicationId}`)
          } catch (routerError) {
            console.error('路由跳转失败:', routerError)
            ElMessage.error('跳转失败，请手动访问结果页面')
          }
        }
      } catch (error) {
        console.error('nextStage执行失败:', error)
        ElMessage.error('操作失败: ' + (error.message || '未知错误'))
      }
    }

    // 生命周期
    onMounted(async () => {
      if (!applicationId) {
        ElMessage.error('缺少申请ID参数')
        router.push('/candidate/dashboard')
        return
      }
      
      // 首先检查面试状态
      await checkInterviewStatus()
      
      // 如果面试已锁定，不继续加载其他内容
      if (isInterviewLocked.value) {
        ElMessage.info('面试已完成，无法继续答题')
        return
      }
      
      // 加载简历信息
      await loadResumeInfo()
      
      // 根据当前阶段加载对应的题目
      const currentStageId = currentStage.value.id
      if (currentStageId === 'logic') {
        await loadLogicQuestions()
      } else if (['innovation', 'professional', 'pressure'].includes(currentStageId)) {
        await loadVideoQuestions(currentStageId)
      }
      
      // 加载语音配置
      await loadVoiceProfiles()
      
      startTimer()
      
      // 启动状态检查定时器
      startStatusCheckTimer()
    })
    
    onUnmounted(() => {
      // 清理定时器
      clearStatusCheckTimer()
    })
    
    return {
      currentStageIndex,
      currentQuestionIndex,
      isRecording,
      recordingTime,
      timeRemaining,
      pressureLevel,
      selfIntroductionVideo,
      loading,
      applicationId,
      answers,
      recordings,
      audioRecordings,
      logicAnswers,
      uploadedVideoUrls,
      interview,
      candidateInfo,
      stages,
      logicQuestions,
      innovationQuestions,
      professionalQuestions,
      pressureQuestions,
      skipSections,
      currentPressureScenario,
      interviewStatus,
      isInterviewLocked,
      interviewProgress,
      statusMessage,
      currentStage,
      progressPercentage,
      overallProgress,
      currentQuestion,
      isCameraPreviewOn,
      previewVideo,
      formatTime,
      getVideoUrl,
      loadResumeInfo,
      loadLogicQuestions,
      loadVideoQuestions,
      submitSelfIntroduction,
      submitLogicAnswers,
      submitVideoAnswer,
      startSelfIntroduction,
      stopSelfIntroduction,
      retakeVideo,
      previousQuestion,
      nextQuestion,
      startVideoRecording,
      stopVideoRecording,
      retakeVideoRecording,
      confirmVideoRecording,
      startAudioRecording,
      getCurrentVideoCategory,
      previousStage,
      nextStage,
      confirmSelfIntroVideo,
      startCameraPreview,
      stopCameraPreview,
      closeAllCameras,
      
      // 新增：AI分析结果
      aiAnalysisResults,
      analysisLoading,
      showAnalysisResults,
      videoUploadStatus,
      
      // 新增方法
      getInterviewResults,
      generateReport,
      
      // 语音相关
      showVoiceSelector,
      selectedVoiceProfile,
      availableVoiceProfiles,
      isPlayingAudio,
      testingVoice,
      playQuestionAudio,
      selectVoiceProfile,
      confirmVoiceSelection,
      testVoice,
      
      // 面部表情分析相关
      onExpressionAnalysisComplete,
      onExpressionAnalysisError
    }
  }
}
</script>

<style scoped>
.interview-session-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20px;
}

.interview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.company-info h1 {
  color: #333;
  margin: 0 0 8px 0;
}

.company-info p {
  color: #666;
  margin: 0;
}

.interview-progress {
  text-align: right;
  min-width: 200px;
}

.stage-navigation {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stage-steps {
  width: 100%;
}

.stage-content {
  background: white;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.question-actions {
  display: flex;
  gap: 8px;
}

.voice-selector {
  padding: 20px 0;
}

.voice-profiles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.voice-profile-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  transition: all 0.3s;
  cursor: pointer;
}

.voice-profile-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.voice-profile-card.is-selected {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.voice-profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.voice-type {
  font-size: 12px;
  color: #666;
  background-color: #f5f5f5;
  padding: 2px 8px;
  border-radius: 4px;
}

.voice-profile-content h5 {
  margin: 0 0 8px 0;
  color: #333;
}

.voice-profile-content p {
  margin: 0 0 12px 0;
  color: #666;
  font-size: 14px;
}

.voice-params {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #999;
}

.voice-profile-actions {
  margin-top: 12px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

.skip-section {
  text-align: center;
  padding: 40px;
}

.duration-info {
  color: #666;
  font-size: 14px;
  margin-left: 12px;
}

.example-section {
  margin: 16px 0;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #409eff;
}

.example-section h5 {
  margin: 0 0 8px 0;
  color: #409eff;
  font-size: 14px;
}

.example-text {
  margin: 0;
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

.criteria-section {
  margin: 16px 0;
  padding: 12px;
  background: #fff7e6;
  border-radius: 6px;
  border-left: 4px solid #faad14;
}

.criteria-section h5 {
  margin: 0 0 8px 0;
  color: #faad14;
  font-size: 14px;
}

.criteria-text {
  margin: 0;
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

.stage-content {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  min-height: 600px;
}

.stage-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.stage-header h2 {
  color: #333;
  margin: 0;
}

.timer {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  color: #666;
}

.resume-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
}

.resume-display h3,
.self-introduction h3 {
  color: #333;
  margin-bottom: 20px;
}

.skill-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.video-recording {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.recording-controls {
  display: flex;
  gap: 12px;
}

.recording-timer {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #ff6b6b;
  font-weight: bold;
}

.video-preview {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 16px;
}

.video-preview video {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.video-actions {
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
}

.recording-controls {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.recording-timer {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #ff6b6b;
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 16px;
}

.recording-area {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 2px dashed #e4e7ed;
  transition: border-color 0.3s;
}

.recording-area:hover {
  border-color: #409eff;
}

.audio-preview {
  margin-top: 16px;
}

.audio-preview audio {
  width: 100%;
  border-radius: 4px;
}

.camera-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.camera-preview video {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.preview-controls {
  display: flex;
  gap: 8px;
}

.loading-section {
  text-align: center;
  padding: 40px;
}

.loading-section p {
  margin-top: 20px;
  color: #666;
  font-size: 16px;
}

.error-section {
  text-align: center;
  padding: 40px;
}

.question-navigation {
  display: flex;
  justify-content: space-between;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.multiple-choice {
  margin: 20px 0;
}

.option-radio {
  display: block;
  margin-bottom: 12px;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  transition: all 0.3s;
}

.option-radio:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.option-radio.is-checked {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.fill-blank {
  margin: 20px 0;
}

.question-section {
  max-width: 800px;
  margin: 0 auto;
}

.question-counter {
  text-align: center;
  margin-bottom: 20px;
  color: #666;
}

.question-content {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
}

.question-content h3 {
  color: #333;
  margin-bottom: 16px;
}

.question-text {
  font-size: 16px;
  line-height: 1.6;
  color: #333;
  margin-bottom: 24px;
}

.multiple-choice {
  margin: 20px 0;
}

.option-radio {
  display: block;
  margin-bottom: 12px;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  transition: all 0.3s;
}

.option-radio:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.option-radio.is-checked {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.fill-blank {
  margin: 20px 0;
}

.multi-round-questions,
.skill-questions,
.pressure-questions {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.question-round,
.skill-question,
.pressure-question {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  background: #f8f9fa;
}

.round-header,
.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.round-header h3,
.question-header h3,
.question-header h4 {
  color: #333;
  margin: 0;
}

.skill-tags {
  display: flex;
  gap: 8px;
}

.answer-section {
  margin-top: 20px;
}

.recording-area {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.recording-controls {
  display: flex;
  gap: 12px;
}

.video-preview,
.audio-preview {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.pressure-indicator {
  display: flex;
  align-items: center;
  gap: 16px;
}

.pressure-label {
  color: #666;
  font-weight: 500;
}

.scenario-description {
  background: #fff3cd;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
  border-left: 4px solid #ffc107;
}

.scenario-description h3 {
  color: #856404;
  margin-bottom: 12px;
}

.scenario-description p {
  color: #856404;
  margin: 0;
}

.intensity-indicator {
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.intensity-1 { background: #d4edda; color: #155724; }
.intensity-2 { background: #d1ecf1; color: #0c5460; }
.intensity-3 { background: #fff3cd; color: #856404; }
.intensity-4 { background: #f8d7da; color: #721c24; }
.intensity-5 { background: #f5c6cb; color: #721c24; }

.stage-footer {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.progress-info {
  flex: 1;
  margin-right: 30px;
}

.progress-info span {
  color: #333;
  font-weight: 500;
  margin-bottom: 8px;
  display: block;
}

.footer-actions {
  display: flex;
  gap: 12px;
}

/* 面试状态警告样式 */
.interview-status-alert {
  margin: 20px 0;
}

/* 视频上传状态指示器样式 */
.upload-status {
  margin: 16px 0;
  padding: 12px;
  border-radius: 8px;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
}

.status-item.uploading {
  color: #409eff;
}

.status-item.analyzing {
  color: #e6a23c;
}

.status-item.completed {
  color: #67c23a;
}

.status-item.error {
  color: #f56c6c;
}

/* AI分析结果样式 */
.ai-analysis-results {
  margin: 20px 0;
  padding: 20px;
  border-radius: 8px;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border: 1px solid #bae6fd;
}

.analysis-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.analysis-header h4 {
  margin: 0;
  color: #0369a1;
  font-size: 16px;
  font-weight: 600;
}

.scores-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 16px;
}

.score-item {
  background: white;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #e0f2fe;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.score-label {
  font-size: 14px;
  color: #64748b;
  margin-bottom: 8px;
  font-weight: 500;
}

.score-value {
  font-size: 24px;
  font-weight: 700;
  color: #0369a1;
  margin-bottom: 12px;
}

.analysis-message {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background: rgba(59, 130, 246, 0.1);
  border-radius: 6px;
  color: #1e40af;
  font-size: 14px;
}

.analysis-message .el-icon {
  color: #3b82f6;
}

/* 视频操作按钮样式优化 */
.video-actions {
  display: flex;
  gap: 8px;
  margin-top: 12px;
}

.video-actions .el-button {
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .scores-grid {
    grid-template-columns: 1fr;
  }
  
  .ai-analysis-results {
    padding: 16px;
  }
  
  .analysis-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style> 